package com.joyd.autobot

import android.content.SharedPreferences
import android.os.Bundle
import android.preference.PreferenceManager
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class SettingsActivity : AppCompatActivity() {

    private lateinit var sharedPreferences: SharedPreferences
    private lateinit var webSocketUrlEditText: EditText
    private lateinit var saveButton: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_settings)

        // 初始化Preferences
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)

        // 绑定UI组件
        webSocketUrlEditText = findViewById(R.id.web_socket_url_edit_text)
        saveButton = findViewById(R.id.save_settings_btn)

        // 加载保存的设置
        loadSavedSettings()

        // 设置保存按钮的点击事件
        saveButton.setOnClickListener {
            saveSettings()
        }
    }

    private fun loadSavedSettings() {
        // 加载保存的WebSocket地址，如果没有保存则使用默认地址
        val defaultUrl = "ws://192.168.2.236:8805"
        val webSocketUrl = sharedPreferences.getString(getString(R.string.pref_key_web_socket_url), defaultUrl)
        webSocketUrlEditText.setText(webSocketUrl)
    }

    private fun saveSettings() {
        // 获取用户输入的WebSocket地址
        val webSocketUrl = webSocketUrlEditText.text.toString().trim()

        // 简单验证URL格式
        if (webSocketUrl.isEmpty() || !isValidWebSocketUrl(webSocketUrl)) {
            Toast.makeText(this, "请输入有效的WebSocket地址", Toast.LENGTH_SHORT).show()
            return
        }

        // 保存设置
        with(sharedPreferences.edit()) {
            putString(getString(R.string.pref_key_web_socket_url), webSocketUrl)
            apply()
        }

        Log.d("SettingsActivity", "保存WebSocket地址: $webSocketUrl")
        Toast.makeText(this, "设置已保存", Toast.LENGTH_SHORT).show()

        // 设置结果码为OK
        setResult(RESULT_OK)
        
        // 关闭Activity
        finish()
    }

    private fun isValidWebSocketUrl(url: String): Boolean {
        // 简单的WebSocket URL验证逻辑
        return url.startsWith("ws://") || url.startsWith("wss://")
    }
}